package alibaba.ifelserefactor.demo01.test04;

import alibaba.ifelserefactor.demo01.ShareType;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import static alibaba.ifelserefactor.demo01.ShareType.*;

/**
 * @author ChangLiang
 * @date 2020/4/20
 */
public class ShareItemFactory {

    private static Map<ShareType, Class<? extends ShareItem>> map = new HashMap<>();


    static {
        map.put(TYPE_LINK, Link.class);
        map.put(TYPE_IMAGE, Image.class);
        map.put(TYPE_TEXT, Text.class);
        map.put(TYPE_IMAGE_TEXT, ImageText.class);
    }

    /**
     * 静态工厂方法
     * @param request
     * @return
     */
    public static ShareItem createShareItem(ShareItemRequest request) {
        try {
            Class<? extends ShareItem> shareItemClass = map.get(request.type);
            Constructor<? extends ShareItem> constructor = shareItemClass.getConstructor(ShareType.class);
            return constructor.newInstance(request.type);
        } catch (Exception e) {

        }
        return null;
    }
}
